<template>
    <div class="operationBasicsDetail">
        <div class="header">
            <van-nav-bar title="添加商品" left-arrow @click-left="handleLeft" v-if="!showSupplierName">
            </van-nav-bar>
        </div>
        <!-- 浮动导航栏 -->
        <div class="hmshop-floating-nav" v-if="showFloatingNav">
            <ul>
                <li @click="scrollToElement('product_detail_top')"
                    :class="{ 'red-text': activeNavItem == 'product_detail_top' }">
                    商品信息
                </li>

                <li @click="scrollToElement('product_detail_title--mechanism')"
                    :class="{ 'red-text': activeNavItem == 'product_detail_title--mechanism' }">
                    直播补充信息
                </li>
                <li @click="scrollToElement('product_detail_title--info')"
                    :class="{ 'red-text': activeNavItem == 'product_detail_title--info' }">
                    商品资质
                </li>

            </ul>
        </div>
        <template v-if="!showSupplierName">
            <div class="product_detail_top--heng " id="product_detail_top--heng"></div>
            <div class="add_product" @scroll="checkScrollPosition">
                <van-form @submit="onSubmit" ref="formRef" validate-first scroll-to-error>
                    <!-- 商品信息 -->
                    <messageBox id="product_detail_top" class="mess_card" title="商品信息" :downShow="false">

                        <div class="form_item">
                            <van-cell-group inset>

                                <van-field input-align="right" error-message-align="right" name="supplierName"
                                    label="供应商名称" v-model="addProductQueryParams.supplierName" readonly
                                    placeholder="请选择" required @click="showSupplierName = true" :rules="[
                                        {
                                            required: true,
                                            trigger: 'onBlur',
                                            message: '请选择供应商名称',
                                        },
                                    ]">
                                    <template #right-icon>
                                        <van-icon name="arrow" size="3.733333vw" color="#B9BABB" />
                                    </template>
                                </van-field>
                            </van-cell-group>
                            <van-cell-group inset>
                                <van-field input-align="right" error-message-align="right" name="styleName"
                                    @input="(e) => { forbidRule(e, 'styleName', 'blank') }" label="商品名称"
                                    v-model="addProductQueryParams.styleName" placeholder="请输入商品名称" required
                                    maxlength="50" :rules="[
                                        { required: true, trigger: 'onBlur', message: '请输入商品名称' }
                                    ]" />
                            </van-cell-group>
                            <van-cell-group inset>
                                <van-field name="productCategoryName" label="商品类目"
                                    v-model="addProductQueryParams.productCategoryName" readonly input-align="right"
                                    error-message-align="right" placeholder="请选择商品类目" @click="show = true" required
                                    :rules="[
                                        { required: true, trigger: 'onBlur', message: '请选择商品类目' },
                                    ]">
                                    <template #right-icon>
                                        <van-icon name="arrow" size="3.733333vw" color="#B9BABB" />
                                    </template>
                                </van-field>
                                <div class="cascaderShade" v-if="cascaderShade"></div>
                                <van-popup v-model:show="show" round position="bottom">
                                    <van-cascader v-model="cascaderValue" title="请选择商品类目" :options="options"
                                        @close="show = false" @finish="onFinish" />
                                </van-popup>
                            </van-cell-group>
                            <van-cell-group inset>
                                <van-field name="brandName" input-align="right" error-message-align="right" label="品牌"
                                    v-model="addProductQueryParams.brandName" placeholder="请输入品牌名称" maxlength="50"
                                    :rules="[
                                        { required: false, trigger: 'onBlur', message: '请输入品牌名称' },
                                        {
                                            validator: validatorNumberBrand,
                                            message: '请输入正确的品牌名称',
                                        },
                                    ]" />
                            </van-cell-group>
                            <formNumberKeyboard :formRef="formRef" name="styleCode" label="69码"
                                v-model:keyValue="addProductQueryParams.styleCode" placeholder="请输入69码" :rules="[
                                    {
                                        validator: validatorStyleCode,
                                        message: '请输入正确内容',
                                    },
                                ]">
                            </formNumberKeyboard>
                            <van-cell-group inset>
                                <van-field input-align="right" error-message-align="right" name="tradeMode" label="贸易方式"
                                    v-model="addProductQueryParams.tradeMode" required :rules="[
                                        { required: true, trigger: 'onBlur', message: '请选择贸易方式' },
                                    ]">
                                    <template #input>
                                        <van-radio-group v-model="tradeModeChecked" direction="horizontal">
                                            <van-radio v-for="item in tradeModeColumns" :key="item.value"
                                                :name="item.value">{{
                                                    item.text }}</van-radio>
                                        </van-radio-group>
                                    </template>
                                </van-field>
                            </van-cell-group>
                            <formNumberKeyboard :formRef="formRef" name="tax" label="平台扣点"
                                v-model:keyValue="addProductQueryParams.tax" placeholder="请输入" required :rules="[
                                    { required: true, trigger: 'onBlur', message: '请输入平台扣点' },
                                    {
                                        validator: validatorcommission,
                                        message: '请输入正确内容：整数或者保留两位小数',
                                    },
                                ]" extraKey=".">
                                <div style="display: flex;align-items: center;">
                                    <span style="margin-right: 5px;">%</span>
                                    <PointButton @onClick="isPoint = true" />
                                </div>
                            </formNumberKeyboard>
                            <van-cell-group inset>
                                <van-field input-align="right" error-message-align="right" name="discountPrice"
                                    label="能否破价" v-model="addProductQueryParams.discountPrice" required :rules="[
                                        { required: true, trigger: 'onBlur', message: '请选择能否破价' },
                                    ]">
                                    <template #input>
                                        <van-radio-group v-model="discountPriceChecked" direction="horizontal">
                                            <van-radio v-for="item in discountPriceColumns" :key="item.value"
                                                :name="item.value">{{
                                                    item.text }}</van-radio>
                                        </van-radio-group>
                                    </template>
                                </van-field>
                            </van-cell-group>
                            <van-cell-group inset>
                                <van-field input-align="right" error-message-align="right" name="specs" label="规格/材质"
                                    v-model="addProductQueryParams.specs" placeholder="请输入规格/材质名称" required
                                    maxlength="200" :rules="[
                                        { required: true, trigger: 'onBlur', message: '请输入规格/材质名称' },
                                    ]" @input="(e) => { forbidRule(e, 'specs', 'emoji') }" />
                            </van-cell-group>

                            <van-cell-group inset v-if="hm_warehouse_show">
                                <van-field input-align="right" error-message-align="right" name="warehouse" label="走仓"
                                    required :rules="[
                                        { required: true, trigger: 'onBlur', message: '请选择是否走仓' },
                                    ]" v-model="addProductQueryParams.warehouse">
                                    <template #input>
                                        <van-radio-group v-model="warehouseChecked" direction="horizontal">
                                            <van-radio v-for="item in discountWarehouse" :key="item.value"
                                                :name="item.value">{{
                                                    item.text }}</van-radio>
                                        </van-radio-group>
                                    </template>
                                </van-field>
                            </van-cell-group>
                            <formNumberKeyboard :formRef="formRef" name="historyPrice" label="历史最低售价"
                                v-model:keyValue="addProductQueryParams.historyPrice" placeholder="请输入历史最低售价" :rules="[
                                    {
                                        required: false,
                                        trigger: 'onBlur',
                                        message: '请输入历史最低售价',
                                    },
                                    {
                                        validator: validatorPrice,
                                        message: '请输入正确的历史最低售价',
                                    },
                                ]" extraKey="." />

                            <van-cell-group inset>
                                <van-field v-model="addProductQueryParams.groupName" input-align="right"
                                    error-message-align="right" maxlength="20" autosize label="对接群名"
                                    @input="(e) => { forbidRule(e, 'groupName', 'emoji') }" placeholder="请输入对接群名" />
                            </van-cell-group>

                            <van-cell-group inset>
                                <van-field v-model="addProductQueryParams.sellingPoints" input-align="right" name="sellingPoints"
                                    error-message-align="right" rows="3" autosize label="卖点" type="textarea"
                                    @input="(e) => { forbidRule(e, 'sellingPoints', 'emoji') }" placeholder="请输入卖点"
                                    required :rules="[
                                        { validator: validSpace, message: '请输入卖点' }
                                    ]" />
                            </van-cell-group>
                        </div>
                    </messageBox>
                    <!-- 机制 -->
                    <div id="product_detail_title--jizhi">
                        <messageBox class="mess_card mt-10">
                            <template #titleBox>
                                <div class="message_title_box">
                                    <div class="chilunimg"></div>
                                    <div class="jz1_img"></div>
                                </div>
                            </template>
                            <div class="form_item">
                                <van-cell-group inset>
                                    <van-field input-align="right" error-message-align="right" name="cooperationMode"
                                        label="合作方式" v-model="addProductQueryParams.cooperationMode" readonly
                                        placeholder="请选择" required :rules="[
                                            { required: true, trigger: 'onBlur', message: '请选择合作方式' },
                                        ]">
                                        <template #input>
                                            <van-radio-group v-model="addProductQueryParams.cooperationMode"
                                                direction="horizontal">
                                                <van-radio v-for="item in cooperationModeColumns" :key="item.value"
                                                    :name="item.value">{{
                                                        item.text }}</van-radio>
                                            </van-radio-group>
                                        </template>
                                    </van-field>
                                </van-cell-group>
                                <van-cell-group inset>
                                    <van-field input-align="right" error-message-align="right"
                                        name="liveStreamingMechanism" label="机制" maxlength="12"
                                        v-model="addProductQueryParams.liveStreamingMechanism"
                                        @input="(e) => { forbidRule(e, 'liveStreamingMechanism', 'blank') }"
                                        placeholder="请输入机制" required :rules="[
                                            { required: true, trigger: 'onBlur', message: '请输入机制' },
                                        ]" />
                                </van-cell-group>
                                <formNumberKeyboard :formRef="formRef"
                                    v-if="addProductQueryParams.cooperationMode == '分佣'" name="price" label="售价"
                                    v-model:keyValue="addProductQueryParams.price" placeholder="请输入售价" required :rules="[
                                        { required: true, trigger: 'onBlur', message: '请输入售价' },
                                        {
                                            validator: validatorNumber,
                                            message: '请输入正确内容：整数或者保留两位小数',
                                        },
                                    ]" extraKey="." />
                                <formNumberKeyboard :formRef="formRef"
                                    v-if="addProductQueryParams.cooperationMode == '分佣'" name="commission" label="佣金"
                                    v-model:keyValue="addProductQueryParams.commission" placeholder="请输入" required
                                    :rules="[
                                        { required: true, trigger: 'onBlur', message: '请输入佣金' },
                                        {
                                            validator: validatorcommission,
                                            message: '请输入正确内容：整数或者保留两位小数',
                                        },
                                    ]" extraKey=".">
                                    %
                                </formNumberKeyboard>
                                <formNumberKeyboard :formRef="formRef"
                                    v-if="addProductQueryParams.cooperationMode == '分佣'" name="brokerage" label="补充佣金"
                                    v-model:keyValue="addProductQueryParams.brokerage" placeholder="请输入" :rules="[
                                        {
                                            validator: validatorbrokerage,
                                            message: '请输入正确内容：整数或者保留两位小数',
                                        },
                                    ]" extraKey=".">
                                    %
                                </formNumberKeyboard>
                                <van-cell-group inset v-if="addProductQueryParams.cooperationMode == '分佣'">
                                    <van-field input-align="right" error-message-align="right" name="costPrice"
                                        label="成本" v-model="addProductQueryParams.costPrice" readonly
                                        placeholder="请输入" />
                                </van-cell-group>
                                <formNumberKeyboard v-else :formRef="formRef" name="costPrice" label="成本"
                                    v-model:keyValue="addProductQueryParams.costPrice" placeholder="请输入"
                                    :required="addProductQueryParams.cooperationMode == '供货'" :rules="[
                                        {
                                            validator: validatorNumbercostPrice,
                                            message: '请输入正确内容：整数或者保留两位小数',
                                        },
                                    ]" extraKey="." />
                            </div>
                        </messageBox>

                        <div class="add_jizhi_bt" @click="addMechanism(2)" v-if="mechanismArr.length == 1">
                            <div class="add_img"></div>
                            <div>添加机制</div>
                        </div>

                        <messageBox class="mess_card mt-10" v-if="mechanismArr.indexOf(2) !== -1">
                            <template #titleBox>
                                <div class="message_title_box">
                                    <div class="chilunimg"></div>
                                    <div class="jz2_img"></div>
                                </div>
                            </template>
                            <div class="form_item">
                                <van-cell-group inset>
                                    <van-field input-align="right" error-message-align="right" name="cooperationMode2"
                                        label="合作方式" v-model="addProductQueryParams.cooperationMode2" readonly
                                        placeholder="请选择" clearable :rules="[
                                            { required: false, trigger: 'onBlur', message: '请选择合作方式' },
                                        ]">
                                        <template #input>
                                            <van-radio-group v-model="addProductQueryParams.cooperationMode2"
                                                direction="horizontal">
                                                <van-radio v-for="item in cooperationModeColumns" :key="item.value"
                                                    :name="item.value">{{
                                                        item.text }}</van-radio>
                                            </van-radio-group>
                                        </template>
                                    </van-field>
                                </van-cell-group>
                                <van-cell-group inset>
                                    <van-field input-align="right" error-message-align="right"
                                        name="liveStreamingMechanism2" label="机制" maxlength="12"
                                        v-model="addProductQueryParams.liveStreamingMechanism2"
                                        :required="!!addProductQueryParams.cooperationMode2"
                                        @input="(e) => { forbidRule(e, 'liveStreamingMechanism2', 'blank') }"
                                        placeholder="请输入" :rules="[
                                            { validator: validators2, message: '请输入机制' },
                                        ]" />
                                </van-cell-group>
                                <formNumberKeyboard :formRef="formRef"
                                    v-if="addProductQueryParams.cooperationMode2 == '分佣'" name="price2" label="售价"
                                    v-model:keyValue="addProductQueryParams.price2" placeholder="请输入"
                                    :required="addProductQueryParams.cooperationMode2 == '分佣'" :rules="[
                                        { validator: validators2, message: '请输入售价' },
                                        {
                                            validator: validatorNumber2,
                                            message: '请输入正确内容：整数或者保留两位小数',
                                        },
                                    ]" extraKey="." />
                                <formNumberKeyboard :formRef="formRef"
                                    v-if="addProductQueryParams.cooperationMode2 == '分佣'" name="commission2" label="佣金"
                                    v-model:keyValue="addProductQueryParams.commission2" placeholder="请输入"
                                    :required="addProductQueryParams.cooperationMode2 == '分佣'" :rules="[
                                        { validator: validators2, message: '请输入佣金' },
                                        {
                                            validator: validatorcommission2,
                                            message: '请输入正确内容：整数或者保留两位小数',
                                        },
                                    ]" extraKey=".">
                                    %
                                </formNumberKeyboard>
                                <formNumberKeyboard :formRef="formRef"
                                    v-if="addProductQueryParams.cooperationMode2 == '分佣'" name="brokerage2" label="补充佣金"
                                    v-model:keyValue="addProductQueryParams.brokerage2" placeholder="请输入" :rules="[
                                        {
                                            validator: validatorbrokerage2,
                                            message: '请输入正确内容：整数或者保留两位小数',
                                        },
                                    ]" extraKey=".">
                                    %
                                </formNumberKeyboard>
                                <van-cell-group inset v-if="addProductQueryParams.cooperationMode2 == '分佣'">
                                    <van-field input-align="right" error-message-align="right" name="costPrice2"
                                        label="成本" v-model="addProductQueryParams.costPrice2" readonly
                                        placeholder="请输入" />
                                </van-cell-group>
                                <formNumberKeyboard v-else :formRef="formRef" name="costPrice2" label="成本"
                                    v-model:keyValue="addProductQueryParams.costPrice2" placeholder="请输入"
                                    :required="addProductQueryParams.cooperationMode2 == '供货'" :rules="[
                                        {
                                            validator: validatorNumbercostPrice2,
                                            message: '请输入正确内容：整数或者保留两位小数',
                                        },
                                    ]" extraKey="." />

                                <div class="del_jizhi_bt" @click="deleteMechanism(2)">
                                    <div class="del_img"></div>
                                    <div>删除机制</div>
                                </div>
                            </div>
                        </messageBox>

                        <div class="add_jizhi_bt" @click="addMechanism(3)" v-if="mechanismArr.length == 2">
                            <div class="add_img"></div>
                            <div>添加机制</div>
                        </div>

                        <messageBox class="mess_card mt-10" v-if="mechanismArr.indexOf(3) !== -1">
                            <template #titleBox>
                                <div class="message_title_box">
                                    <div class="chilunimg"></div>
                                    <div class="jz3_img"></div>
                                </div>
                            </template>
                            <div class="form_item">
                                <van-cell-group inset>
                                    <van-field input-align="right" error-message-align="right" name="cooperationMode3"
                                        label="合作方式" v-model="addProductQueryParams.cooperationMode3" readonly
                                        placeholder="请选择" :rules="[
                                            { required: false, trigger: 'onBlur', message: '请选择合作方式' },
                                        ]">
                                        <template #input>
                                            <van-radio-group v-model="addProductQueryParams.cooperationMode3"
                                                direction="horizontal">
                                                <van-radio v-for="item in cooperationModeColumns" :key="item.value"
                                                    :name="item.value">{{
                                                        item.text }}</van-radio>
                                            </van-radio-group>
                                        </template>
                                    </van-field>
                                </van-cell-group>
                                <van-cell-group inset>
                                    <van-field input-align="right" error-message-align="right"
                                        name="liveStreamingMechanism3" label="机制" maxlength="12"
                                        v-model="addProductQueryParams.liveStreamingMechanism3"
                                        @input="(e) => { forbidRule(e, 'liveStreamingMechanism3', 'blank') }"
                                        placeholder="请输入" :required="!!addProductQueryParams.cooperationMode3" :rules="[
                                            { validator: validators3, message: '请输入机制' },
                                        ]" />
                                </van-cell-group>
                                <formNumberKeyboard :formRef="formRef"
                                    v-if="addProductQueryParams.cooperationMode3 == '分佣'" name="price3" label="售价"
                                    :required="addProductQueryParams.cooperationMode3 == '分佣'"
                                    v-model:keyValue="addProductQueryParams.price3" placeholder="请输入" :rules="[
                                        { validator: validators3, message: '请输入售价' },
                                        {
                                            validator: validatorNumber2,
                                            message: '请输入正确内容：整数或者保留两位小数',
                                        },
                                    ]" extraKey="." />
                                <formNumberKeyboard :formRef="formRef"
                                    v-if="addProductQueryParams.cooperationMode3 == '分佣'" name="commission3" label="佣金"
                                    :required="addProductQueryParams.cooperationMode3 == '分佣'"
                                    v-model:keyValue="addProductQueryParams.commission3" placeholder="请输入" :rules="[
                                        { validator: validators3, message: '请输入佣金' },
                                        {
                                            validator: validatorcommission2,
                                            message: '请输入正确内容：整数或者保留两位小数',
                                        },
                                    ]" extraKey=".">
                                    %
                                </formNumberKeyboard>
                                <formNumberKeyboard :formRef="formRef"
                                    v-if="addProductQueryParams.cooperationMode3 == '分佣'" name="brokerage3" label="补充佣金"
                                    v-model:keyValue="addProductQueryParams.brokerage3" placeholder="请输入" :rules="[
                                        {
                                            validator: validatorbrokerage3,
                                            message: '请输入正确内容：整数或者保留两位小数',
                                        },
                                    ]" extraKey=".">
                                    %
                                </formNumberKeyboard>
                                <van-cell-group inset v-if="addProductQueryParams.cooperationMode3 == '分佣'">
                                    <van-field input-align="right" error-message-align="right" name="costPrice3"
                                        label="成本" v-model="addProductQueryParams.costPrice3" readonly
                                        placeholder="请输入" />
                                </van-cell-group>
                                <formNumberKeyboard v-else :formRef="formRef" name="costPrice3" label="成本"
                                    v-model:keyValue="addProductQueryParams.costPrice3" placeholder="请输入"
                                    :required="addProductQueryParams.cooperationMode3 == '供货'" :rules="[
                                        {
                                            validator: validatorNumbercostPrice3,
                                            message: '请输入正确内容：整数或者保留两位小数',
                                        },
                                    ]" extraKey="." />
                                <div class="del_jizhi_bt" @click="deleteMechanism(3)">
                                    <div class="del_img"></div>
                                    <div>删除机制</div>
                                </div>
                            </div>
                        </messageBox>
                    </div>
                    <!-- 直播补充信息 -->
                    <messageBox id="product_detail_title--mechanism" class="mess_card" title="直播补充信息" :downShow="false">
                        <div class="form_item">

                            <van-cell-group inset>
                                <van-field input-align="right" error-message-align="right" name="deliveryTime"
                                    label="发货时间" v-model="addProductQueryParams.deliveryTime" placeholder="请输入发货时间(预售)"
                                    maxlength="48" @input="(e) => { forbidRule(e, 'deliveryTime', 'emoji') }" required
                                    :rules="[
                                        { required: true, trigger: 'onBlur', message: '请输入发货时间' }
                                    ]" />
                            </van-cell-group>
                            <van-cell-group inset>
                                <van-field input-align="right" error-message-align="right" name="eligibility"
                                    label="发货地" v-model="addProductQueryParams.placeDelivery" placeholder="请输入发货地"
                                    maxlength="100" @input="(e) => { forbidRule(e, 'placeDelivery', 'emoji') }" />

                            </van-cell-group>
                            <van-cell-group inset>
                                <van-field input-align="right" error-message-align="right" name="logistics"
                                    label="物流/快递" :rules="[
                                        { required: false, trigger: 'onBlur', message: '请输入商品物流/快递' },
                                    ]" v-model="addProductQueryParams.logistics" placeholder="请输入" maxlength="20"
                                    @input="(e) => { forbidRule(e, 'logistics', 'emoji') }" />
                            </van-cell-group>
                            <van-cell-group inset>

                                <van-field input-align="right" error-message-align="right" name="eligibility"
                                    label="适用人群" v-model="addProductQueryParams.eligibility" placeholder="请输入"
                                    maxlength="20" @input="(e) => { forbidRule(e, 'eligibility', 'emoji') }" />
                            </van-cell-group>
                            <formNumberKeyboard :formRef="formRef" name="factoryStockNum" label="厂家可用库存"
                                v-model:keyValue="addProductQueryParams.factoryStockNum" placeholder="请输入" maxlength="8"
                                required :rules="[
                                    { required: true, trigger: 'onBlur', message: '请输入厂家可用库存' }
                                ]" />
                            <van-cell-group inset>
                                <van-field v-model="addProductQueryParams.noSendArea" input-align="right"
                                    error-message-align="right" maxlength="72" rows="1" autosize label="不发货地区"
                                    @input="(e) => { forbidRule(e, 'noSendArea', 'emoji') }" placeholder="请输入不发货地区" />
                            </van-cell-group>
                        </div>
                    </messageBox>
                    <!-- 商品资质 -->
                    <messageBox id="product_detail_title--info" class="mess_card" title="商品资质" :downShow="false">
                        <div class="form_item imgform">

                            <div class="image-title">
                                商品图
                            </div>
                            <van-cell-group inset>
                                <van-field name="商品图" label="" v-model="addProductQueryParams.productImage">
                                    <template #input>
                                        <div class="value">
                                            <draggable class='dragge_box' :list="productImageList" ghost-class="ghost"
                                                chosen-class="chosenClass" animation="300" :delay="300" @start="onStart"
                                                @end="onEnd">
                                                <template #item="{ element, index }">
                                                    <div class="imgList">
                                                        <div class="loading_pic" v-if="!element.url">
                                                            <van-loading type="spinner" size="20" />
                                                        </div>
                                                        <van-image
                                                            :src="element.url + '?x-oss-process=image/resize,w_300'"
                                                            @click="enlargeImage(element.url)"
                                                            v-if="element.url"></van-image>
                                                        <van-icon name="cross" color="#fff" v-if="element.url"
                                                            @click.prevent="
                                                                deleteImg(
                                                                    productImageList,
                                                                    index,
                                                                )
                                                                " />
                                                    </div>
                                                </template>
                                            </draggable>
                                            <van-image :src="upload" v-if="productImageList.length < 5"
                                                @click="postImage('productImage', 5)" v-throttle:click></van-image>
                                        </div>
                                    </template>
                                </van-field>

                            </van-cell-group>
                            <div class="image-title">
                                备案凭证/行政许可批件
                            </div>
                            <van-cell-group inset>
                                <van-field name="备案凭证/行政许可批件" label="" v-model="addProductQueryParams.voucherImage">
                                    <template #input>
                                        <div class="value">
                                            <draggable class='dragge_box' :list="voucherImageList" ghost-class="ghost"
                                                chosen-class="chosenClass" animation="300" :delay="300" @start="onStart"
                                                @end="onEnd">
                                                <template #item="{ element, index }">
                                                    <div class="imgList">
                                                        <div class="loading_pic" v-if="!element.url">
                                                            <van-loading type="spinner" size="20" />
                                                        </div>
                                                        <van-image
                                                            :src="element.url + '?x-oss-process=image/resize,w_300'"
                                                            @click="enlargeImage(element.url)"
                                                            v-if="element.url"></van-image>
                                                        <van-icon name="cross" color="#fff" v-if="element.url"
                                                            @click.prevent="
                                                                deleteImg(
                                                                    voucherImageList,
                                                                    index,
                                                                )
                                                                " />
                                                    </div>
                                                </template>
                                            </draggable>

                                            <van-image :src="upload" v-if="voucherImageList.length < 5"
                                                @click="postImage('voucherImage', 5)" v-throttle:click></van-image>
                                        </div>
                                    </template>
                                </van-field>
                            </van-cell-group>
                            <div class="image-title">
                                其他资质
                            </div>
                            <van-cell-group inset>
                                <van-field name="其他资质" label="" v-model="addProductQueryParams.otherImage">
                                    <template #input>
                                        <div class="value">
                                            <draggable class='dragge_box' :list="otherImageList" ghost-class="ghost"
                                                chosen-class="chosenClass" animation="300" :delay="300" @start="onStart"
                                                @end="onEnd">
                                                <template #item="{ element, index }">
                                                    <div class="imgList">
                                                        <div class="loading_pic" v-if="!element.url">
                                                            <van-loading type="spinner" size="20" />
                                                        </div>
                                                        <van-image
                                                            :src="element.url + '?x-oss-process=image/resize,w_300'"
                                                            @click="enlargeImage(element.url)"
                                                            v-if="element.url"></van-image>
                                                        <van-icon name="cross" color="#fff" v-if="element.url"
                                                            @click.prevent="
                                                                deleteImg(
                                                                    otherImageList,
                                                                    index,
                                                                )
                                                                " />
                                                    </div>
                                                </template>
                                            </draggable>

                                            <van-image :src="upload" v-if="otherImageList.length < 10"
                                                @click="postImage('otherImage', 10)" v-throttle:click></van-image>
                                        </div>
                                    </template>
                                </van-field>
                            </van-cell-group>
                            <div class="image-title" v-if="tradeModeChecked == '进口'">
                                进口货物/原材料报关单
                            </div>
                            <van-cell-group inset>
                                <van-field name="进口货物/原材料报关单" label=""
                                    v-model="addProductQueryParams.customsDeclarationImage"
                                    v-if="tradeModeChecked == '进口'">
                                    <template #input>
                                        <div class="value">
                                            <draggable class='dragge_box' :list="customsDeclarationImageList"
                                                ghost-class="ghost" chosen-class="chosenClass" animation="300"
                                                :delay="300" @start="onStart" @end="onEnd">
                                                <template #item="{ element, index }">
                                                    <div class="imgList">
                                                        <div class="loading_pic" v-if="!element.url">
                                                            <van-loading type="spinner" size="20" />
                                                        </div>
                                                        <van-image
                                                            :src="element.url + '?x-oss-process=image/resize,w_300'"
                                                            @click="enlargeImage(element.url)"
                                                            v-if="element.url"></van-image>
                                                        <van-icon name="cross" color="#fff" v-if="element.url"
                                                            @click.prevent="
                                                                deleteImg(
                                                                    customsDeclarationImageList,
                                                                    index,
                                                                )
                                                                " />
                                                    </div>
                                                </template>
                                            </draggable>
                                            <van-image :src="upload" v-if="customsDeclarationImageList.length < 5"
                                                @click="postImage('customsDeclarationImage', 5)"
                                                v-throttle:click></van-image>
                                        </div>
                                    </template>
                                </van-field>
                            </van-cell-group>
                            <div class="image-title" v-if="tradeModeChecked == '进口'">
                                进口产品备案材料
                            </div>
                            <van-cell-group inset>
                                <van-field name="进口产品备案材料" label=""
                                    v-model="addProductQueryParams.customsInformationImage"
                                    v-if="tradeModeChecked == '进口'">
                                    <template #input>
                                        <div class="value">
                                            <draggable class='dragge_box' :list="customsInformationImageList"
                                                ghost-class="ghost" chosen-class="chosenClass" animation="300"
                                                :delay="300" @start="onStart" @end="onEnd">
                                                <template #item="{ element, index }">
                                                    <div class="imgList">
                                                        <div class="loading_pic" v-if="!element.url">
                                                            <van-loading type="spinner" size="20" />
                                                        </div>
                                                        <van-image
                                                            :src="element.url + '?x-oss-process=image/resize,w_300'"
                                                            @click="enlargeImage(element.url)"
                                                            v-if="element.url"></van-image>
                                                        <van-icon name="cross" color="#fff" v-if="element.url"
                                                            @click.prevent="
                                                                deleteImg(
                                                                    customsInformationImageList,
                                                                    index,
                                                                )
                                                                " />
                                                    </div>
                                                </template>
                                            </draggable>
                                            <van-image :src="upload" v-if="customsInformationImageList.length < 5"
                                                @click="postImage('customsInformationImage', 5)"
                                                v-throttle:click></van-image>
                                        </div>
                                    </template>
                                </van-field>
                            </van-cell-group>
                            <div class="image-title" v-if="tradeModeChecked == '进口'">
                                进口产品原材料检验检疫证明
                            </div>
                            <van-cell-group inset>
                                <van-field name="进口产品原材料检验检疫证明" label=""
                                    v-model="addProductQueryParams.customsInspectionImage"
                                    v-if="tradeModeChecked == '进口'">
                                    <template #input>
                                        <div class="value">
                                            <draggable class='dragge_box' :list="customsInspectionImageList"
                                                ghost-class="ghost" chosen-class="chosenClass" animation="300"
                                                :delay="300" @start="onStart" @end="onEnd">
                                                <template #item="{ element, index }">
                                                    <div class="imgList">
                                                        <div class="loading_pic" v-if="!element.url">
                                                            <van-loading type="spinner" size="20" />
                                                        </div>
                                                        <van-image
                                                            :src="element.url + '?x-oss-process=image/resize,w_300'"
                                                            @click="enlargeImage(element.url)"
                                                            v-if="element.url"></van-image>
                                                        <van-icon name="cross" color="#fff" v-if="element.url"
                                                            @click.prevent="
                                                                deleteImg(
                                                                    customsInspectionImageList,
                                                                    index,
                                                                )
                                                                " />
                                                    </div>
                                                </template>
                                            </draggable>
                                            <van-image :src="upload" v-if="customsInspectionImageList.length < 5"
                                                @click="postImage('customsInspectionImage', 5)"
                                                v-throttle:click></van-image>
                                        </div>
                                    </template>
                                </van-field>
                            </van-cell-group>
                            <div class="image-title" v-if="tradeModeChecked == '进口'">
                                检测报告
                            </div>
                            <van-cell-group inset>
                                <van-field name="检测报告" label="" v-if="tradeModeChecked == '进口'"
                                    v-model="addProductQueryParams.customsTestReportImgae">
                                    <template #input>
                                        <div class="value">
                                            <draggable class='dragge_box' :list="customsTestReportImgaeList"
                                                ghost-class="ghost" chosen-class="chosenClass" animation="300"
                                                :delay="300" @start="onStart" @end="onEnd">
                                                <template #item="{ element, index }">
                                                    <div class="imgList">
                                                        <div class="loading_pic" v-if="!element.url">
                                                            <van-loading type="spinner" size="20" />
                                                        </div>
                                                        <van-image
                                                            :src="element.url + '?x-oss-process=image/resize,w_300'"
                                                            @click="enlargeImage(element.url)"
                                                            v-if="element.url"></van-image>
                                                        <van-icon name="cross" color="#fff" v-if="element.url"
                                                            @click.prevent="
                                                                deleteImg(
                                                                    customsTestReportImgaeList,
                                                                    index,
                                                                )
                                                                " />
                                                    </div>
                                                </template>
                                            </draggable>
                                            <van-image :src="upload" v-if="customsTestReportImgaeList.length < 5"
                                                @click="postImage('customsTestReportImgae', 5)"
                                                v-throttle:click></van-image>
                                        </div>
                                    </template>
                                </van-field>
                            </van-cell-group>
                        </div>
                    </messageBox>

                    <div class="form_foot">
                        <van-button round block type="primary" :loading="loading" loading-text="执行中..."
                            native-type="submit" v-throttle:click>
                            保存
                        </van-button>
                    </div>
                </van-form>
            </div>
        </template>

    </div>
    <SupplierScreen :isShow="showSupplierName" @cancel="showSupplierName = false" @submit="onConfirmSupplierName">
    </SupplierScreen>
    <Point :show="isPoint" v-model:costPrice="addProductQueryParams.costPrice"
        v-model:costPrice2="addProductQueryParams.costPrice2" v-model:costPrice3="addProductQueryParams.costPrice3"
        :mechanismArr="mechanismArr" :data="addProductQueryParams" @clone="isPoint = false" />
</template>
<script setup lang="ts">
import {
    getDicts,
    addHmProducts,
    getCategoryList,
} from "@/api/productList/index";
import { showSuccessToast, showFailToast } from "vant";
import { onUnmounted, ref, watchEffect, computed } from "vue";
import { useRouter, useRoute } from "vue-router";
import { loginStore } from "@/store/login";
import { storeToRefs } from "pinia";
import { showImagePreview } from "vant";
import { getEnvValue } from "@/utils/index";
import SupplierScreen from '@/components/SupplierScreen/indexNew.vue'
import formNumberKeyboard from "@/components/formNumberKeyboard/index.vue";
import Point from './components/point.vue'
import PointButton from './components/pointButton.vue'
import draggable from 'vuedraggable';
import { handleImageUpdate } from "@/utils/handleImageUpdate";
import messageBox from '@/views/productDetail/components/messageBox.vue'
const upload = new URL("@/assets/home/upload.png", import.meta.url).href;
//拖拽开始的事件
const onStart = () => {
}
//拖拽结束的事件
const onEnd = () => {
}
const store = loginStore();
const formRef = ref()
const { token } = storeToRefs(store);
const router = useRouter();
const route = useRoute();
const tradeModeChecked = ref();
const addProductQueryParams = ref({
    supplierName: "",
    styleName: "",
    category: "",
    brandName: "",
    styleCode: "",
    sellingPoints: "",
    tradeMode: "",
    cooperationMode: "",
    price: "",
    costPrice: "",
    liveStreamingMechanism: "",
    commission: "",
    brokerage: "",
    productCategoryName: "",
    categoryId: "",

    cooperationMode2: "",
    price2: "",
    costPrice2: "",
    liveStreamingMechanism2: "",
    commission2: "",
    brokerage2: "",

    cooperationMode3: "",
    price3: "",
    costPrice3: "",
    liveStreamingMechanism3: "",
    commission3: "",
    brokerage3: "",

    discountPrice: "",
    supplierId: "",
    productImage: "",
    voucherImage: "",
    otherImage: "",
    customsDeclarationImage: "",
    customsInformationImage: "",
    customsInspectionImage: "",
    customsTestReportImgae: "",
    specs: "",
    // ingredient: "",
    warehouse: "",
    groupName: "",
    deliveryTime: "",
    placeDelivery: "",
    logistics: "",
    eligibility: "",
    factoryStockNum: "",
    noSendArea: "",
    placeDeliveryId: "",
    tax: '',
    historyPrice: ""
});
const isPoint = ref(false)      // 扣点弹框开关
const productImageList = ref<any[]>([]);
const voucherImageList = ref<any[]>([]);
const otherImageList = ref<any[]>([]);
const customsDeclarationImageList = ref<any[]>([]);
const customsInformationImageList = ref<any[]>([]);
const customsInspectionImageList = ref<any[]>([]);
const customsTestReportImgaeList = ref<any[]>([]);

const showSupplierName = ref(false);

const show = ref(false);
const cascaderValue = ref('');
const options = ref();
const tradeModeColumns = ref<any>([]);
const cooperationModeColumns = ref<any>([]);
const discountPriceColumns = ref<any>([]);
const discountPriceChecked = ref()
const discountWarehouse = ref([
    {
        value: 1,
        text: '是',
    },
    {
        value: 0,
        text: '否',
    },

]);
const warehouseChecked = ref()
// 是否显示浮动导航栏
const showFloatingNav = ref(false);
const activeNavItem = ref("");
const scrollToElement = (elementId: string) => {
    const heng: any = (document.querySelector("#product_detail_top--heng") as any).offsetHeight;
    const topOffsetHeight: any = (document.querySelector("#product_detail_top") as any).offsetHeight + heng;

    const mechanismOffsetHeight: any = (document.querySelector("#product_detail_title--mechanism") as any).offsetHeight + heng;

    const firstscoll = topOffsetHeight - 40 + (document.querySelector("#product_detail_title--jizhi") as any).offsetHeight
    const secondscoll = firstscoll + mechanismOffsetHeight

    switch (elementId) {
        case "product_detail_top":
            goScrollTo(0)
            break;
        case "product_detail_title--mechanism":
            goScrollTo(firstscoll)
            break;
        case "product_detail_title--info":
            goScrollTo(secondscoll)
            break;
        default:
            return; // 如果没有匹配的 elementId，直接返回
    }

};
const goScrollTo = (scrollTo) => {
    const el = document.querySelector(".add_product");
    const scrollNow = el!.scrollTop;

    if (scrollNow == scrollTo) {
        return;
    } else {
        el?.scrollTo({ top: scrollTo, behavior: "smooth" })
    }

}
const checkScrollPosition = (event) => {

    // 滚动条距离顶部的距离
    const scrollTop = event?.target.scrollTop;
    // 计算商品内容区域的位置
    const productTopOffset =
        document.getElementById("product_detail_top")?.offsetTop || 0;

    // topOffsetHeight ==> 盒子高度   offsetTop ==> 盒子距离顶部距离 
    const topOffsetHeight: any = (document.querySelector("#product_detail_top") as any).offsetHeight + (document.querySelector("#product_detail_title--jizhi") as any).offsetHeight;

    const mechanismOffsetHeight: any = (document.querySelector("#product_detail_title--mechanism") as any).offsetHeight;

    const heng: any = (document.querySelector("#product_detail_top--heng") as any).offsetHeight;;


    const firstscoll = topOffsetHeight - 40
    const secondscoll = firstscoll + heng
    const thirdscoll = secondscoll + mechanismOffsetHeight + heng
    // 判断滚动位置，设置活动导航项

    if (scrollTop >= 0 && scrollTop < firstscoll) {
        activeNavItem.value = "product_detail_top";
    } else if (scrollTop >= firstscoll && scrollTop < secondscoll) {
        activeNavItem.value = "product_detail_title";
    } else if (scrollTop >= secondscoll && scrollTop < thirdscoll) {
        activeNavItem.value = "product_detail_title--mechanism";
    } else {
        activeNavItem.value = "product_detail_title--info";
    }

    // 根据具体的滚动位置设定条件
    showFloatingNav.value = scrollTop > productTopOffset;
    // showToTopButton.value = scrollTop > 100; // 显示回到顶部按钮条件，例如滚动超过100px
};
const hm_warehouse_show = computed(() => {

    if (addProductQueryParams.value.productCategoryName?.indexOf('饰品') >= 0) {
        return true
    }
    return false
});

const loading = ref(false)

/** 上级路由 */
const fromRoute = computed(() => {
    return route.query.from;
});

watchEffect(() => {
    // 监听平台扣点，售价，佣金，补充佣金，动态计算成本
    if (addProductQueryParams.value.cooperationMode === '分佣' && addProductQueryParams.value.price) {
        let costPrice = Number(addProductQueryParams.value.price || 0) * (1 - ((Number(addProductQueryParams.value.commission || 0) / 100) + (Number(addProductQueryParams.value.brokerage || 0) / 100) + (Number(addProductQueryParams.value.tax || 0) / 100)))
        addProductQueryParams.value.costPrice = costPrice.toFixed(2)
    }
    if (addProductQueryParams.value.cooperationMode2 === '分佣' && addProductQueryParams.value.price2) {
        let costPrice2 = Number(addProductQueryParams.value.price2 || 0) * (1 - ((Number(addProductQueryParams.value.commission2 || 0) / 100) + (Number(addProductQueryParams.value.brokerage2 || 0) / 100) + (Number(addProductQueryParams.value.tax || 0) / 100)))
        addProductQueryParams.value.costPrice2 = costPrice2.toFixed(2)
    }
    if (addProductQueryParams.value.cooperationMode3 === '分佣' && addProductQueryParams.value.price3) {
        let costPrice3 = Number(addProductQueryParams.value.price3 || 0) * (1 - ((Number(addProductQueryParams.value.commission3 || 0) / 100) + (Number(addProductQueryParams.value.brokerage3 || 0) / 100) + (Number(addProductQueryParams.value.tax || 0) / 100)))
        addProductQueryParams.value.costPrice3 = costPrice3.toFixed(2)
    }
})

// 集合
const mechanismArr = ref([1])

// 限制必填情况下空格
const validSpace = (val) => {
    if (val) {
        return !/^[\s]*$/.test(val)
    } else {
        return false
    }
}
// 历史最低售价
const validatorPrice = (val) => {
    if (val) {
        return /(^(?!0\d)([1-9]\d{0,8}(\.\d{1,2})?|0(\.\d{1,2})?)$)/.test(val)
    } else {
        return true
    }
}

const validatorStyleCode = (val) => {
    if (val) {
        return /^[0-9]{3,13}$/.test(val)
    } else {
        return true
    }
}
const validatorNumber = (val) => {
    return /(^(?!0\d)([1-9]\d{0,8}(\.\d{1,2})?|0(\.\d{1,2})?)$)/.test(val);
}

const validatorNumbercostPrice = (val: any) => {
    if (addProductQueryParams.value.cooperationMode == '分佣') {
        if (val) {
            return /(^(?!0\d)([1-9]\d{0,8}(\.\d{1,2})?|0(\.\d{1,2})?)$)/.test(val);
        } else {
            return true
        }
    } else if (addProductQueryParams.value.cooperationMode == '') {
        return true
    } else {
        return /(^(?!0\d)([1-9]\d{0,8}(\.\d{1,2})?|0(\.\d{1,2})?)$)/.test(val);
    }
}

// 机制二机制三  分佣时非必填 为空时非必填 供货时必填
const validatorNumbercostPrice2 = (val) => {
    if (addProductQueryParams.value.cooperationMode2 == '分佣') {
        if (val) {
            return /(^(?!0\d)([1-9]\d{0,8}(\.\d{1,2})?|0(\.\d{1,2})?)$)/.test(val);
        } else {
            return true
        }
    } else if (addProductQueryParams.value.cooperationMode2 == '') {
        return true
    } else {
        return /(^(?!0\d)([1-9]\d{0,8}(\.\d{1,2})?|0(\.\d{1,2})?)$)/.test(val);
    }
}
const validatorNumbercostPrice3 = (val) => {
    if (addProductQueryParams.value.cooperationMode3 == '分佣') {
        if (val) {
            return /(^(?!0\d)([1-9]\d{0,8}(\.\d{1,2})?|0(\.\d{1,2})?)$)/.test(val);
        } else {
            return true
        }
    } else if (addProductQueryParams.value.cooperationMode3 == '') {
        return true
    } else {
        return /(^(?!0\d)([1-9]\d{0,8}(\.\d{1,2})?|0(\.\d{1,2})?)$)/.test(val);
    }
}
// const validatorNumbers = (val) => /^[\u4e00-\u9fa5a-zA-Z0-9]+$/.test(val);
const validatorNumberBrand = (val) => {
    if (val) {
        return /^[\u0020-\u007e\u4e00-\u9fa5]+$/.test(val);
    } else {
        return true
    }
}
const validators2 = (value) => {
    if (addProductQueryParams.value.cooperationMode2) {
        if (value) {
            return true
        } else {
            return false
        }
    } else {
        return true
    }
}
const validators3 = (value) => {
    if (addProductQueryParams.value.cooperationMode3) {
        if (value) {
            return true
        } else {
            return false
        }
    } else {
        return true
    }
}
const validatorNumber2 = (val) => {
    if (val) {
        return /(^(?!0\d)([1-9]\d{0,8}(\.\d{1,2})?|0(\.\d{1,2})?)$)/.test(val);
    } else {
        return true
    }
}

const validatorcommission2 = (val) => {
    if (val) {
        return /^(([1-9]?\d(\.\d{1,2})?)|100|100.00)$/.test(val);
    } else {
        return true
    }
}

const validatorcommission = (val) => /^(([1-9]?\d(\.\d{1,2})?)|100|100.00)$/.test(val);
const validatorbrokerage = (val) => {
    if (addProductQueryParams.value.cooperationMode == '分佣') {
        if (val) {
            return /^(([1-9]?\d(\.\d{1,2})?)|100|100.00)$/.test(val);
        } else {
            return true
        }
    } else {
        return false
    }
}
const validatorbrokerage2 = (val) => {
    if (addProductQueryParams.value.cooperationMode2 == '分佣') {
        if (val) {
            return /^(([1-9]?\d(\.\d{1,2})?)|100|100.00)$/.test(val);
        } else {
            return true
        }
    } else {
        return false
    }
}
const validatorbrokerage3 = (val) => {
    if (addProductQueryParams.value.cooperationMode3 == '分佣') {
        if (val) {
            return /^(([1-9]?\d(\.\d{1,2})?)|100|100.00)$/.test(val);
        } else {
            return true
        }
    } else {
        return false
    }
}

// 输入事件、禁用规则
const forbidRule = (e: any, key: string, type: string) => {
    // 输入法表情默认不能输入
    if (type == 'emoji') {
        // emoji：输入时禁用输入法表情
        addProductQueryParams.value[key] = e.target.value.replace(/[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF][\u200D|\uFE0F]|[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF]|[0-9|*|#]\uFE0F\u20E3|[0-9|#]\u20E3|[\u203C-\u3299]\uFE0F\u200D|[\u203C-\u3299]\uFE0F|[\u2122-\u2B55]|\u303D|[\A9|\AE]\u3030|\u00A9|\u00AE|\u3030/gi, '')
    } else if (type == 'blank') {
        // blank：输入时禁用空格
        addProductQueryParams.value[key] = e.target.value.replace(/\s|[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF][\u200D|\uFE0F]|[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF]|[0-9|*|#]\uFE0F\u20E3|[0-9|#]\u20E3|[\u203C-\u3299]\uFE0F\u200D|[\u203C-\u3299]\uFE0F|[\u2122-\u2B55]|\u303D|[\A9|\AE]\u3030|\u00A9|\u00AE|\u3030/gi, '')
    }
}

/** 添加机制 */
const addMechanism = (index: number) => {
    mechanismArr.value.push(index)
}
/** 删除机制 */
const deleteMechanism = (index: number) => {
    // 当机制二删除并且机制三也存在得情况 删除机制三 保留机制二
    if (index == 2 && mechanismArr.value.length == 3) {
        mechanismArr.value.splice(2, 1)
        addProductQueryParams.value.cooperationMode2 = addProductQueryParams.value.cooperationMode3
        addProductQueryParams.value.price2 = addProductQueryParams.value.price3
        addProductQueryParams.value.costPrice2 = addProductQueryParams.value.costPrice3
        addProductQueryParams.value.liveStreamingMechanism2 = addProductQueryParams.value.liveStreamingMechanism3
        addProductQueryParams.value.commission2 = addProductQueryParams.value.commission3
        addProductQueryParams.value.brokerage2 = addProductQueryParams.value.brokerage3

        addProductQueryParams.value.cooperationMode3 = ""
        addProductQueryParams.value.price3 = ""
        addProductQueryParams.value.costPrice3 = ""
        addProductQueryParams.value.liveStreamingMechanism3 = ""
        addProductQueryParams.value.commission3 = ""
        addProductQueryParams.value.brokerage3 = ""
    } else {
        let indexs = mechanismArr.value.indexOf(index)
        mechanismArr.value.splice(indexs, 1)
        if (index == 2) {
            addProductQueryParams.value.cooperationMode2 = ""
            addProductQueryParams.value.price2 = ""
            addProductQueryParams.value.costPrice2 = ""
            addProductQueryParams.value.liveStreamingMechanism2 = ""
            addProductQueryParams.value.commission2 = ""
            addProductQueryParams.value.brokerage2 = ""
        } else if (index == 3) {
            addProductQueryParams.value.cooperationMode3 = ""
            addProductQueryParams.value.price3 = ""
            addProductQueryParams.value.costPrice3 = ""
            addProductQueryParams.value.liveStreamingMechanism3 = ""
            addProductQueryParams.value.commission3 = ""
            addProductQueryParams.value.brokerage3 = ""
        }
    }
}
/** 获取类目 */
const getOptions = async () => {
    try {
        const res = await getCategoryList();
        const processedData = renameField(res.data);
        options.value = processedData;
    } catch (error) {

        options.value = [];
    }
};
const renameField = (arr: any[]) => {
    return arr.filter(item => item.categoryStatus === 0).map(element => {
        if (element.children) {
            element.children = renameField(element.children);
            if (element.children.length === 0) {
                delete element.children;
            }
        }
        return {
            text: element.categoryName,
            value: element.categoryId,
            ...element,
        };
    });
}
getOptions();

/** 供应商名称关闭 */
const onConfirmSupplierName = (options: any) => {
    showSupplierName.value = false;
    if (options) {
        addProductQueryParams.value.supplierName = options.supplierName
        addProductQueryParams.value.supplierId = options.id;
    }
};
const loadingback = ref(false)
import { onBeforeRouteLeave } from 'vue-router'
// 页面离开路由
onBeforeRouteLeave((_to, from, next) => {
    if (from.meta.title == "添加商品" && loadingback.value == false) {
        // 显示确认对话框
        const confirm = window.confirm('是否退出当前编辑页面，已保存的商品信息将被清空');
        if (confirm) {
            next();
        } else {
            next(false);
        }
    } else {
        next();
    }
});
/** 回退 */
const handleLeft = () => {
    // 商品列表新增返回商品列表
    if (fromRoute.value == 'productList') {
        router.back()
    } else {
        router.push('/home')
    }
}

/** 贸易方式 */
const getTradeMode = async () => {
    const res = await getDicts("hm_trade_type");
    res.data.forEach((element) => {
        element.text = element.dictLabel;
        element.value = element.dictValue;
    });
    tradeModeColumns.value = res.data;
};
getTradeMode();
/** 合作方式 */
const getcooperationMode = async () => {
    const res = await getDicts("hm_cooperation_mode");
    res.data.forEach((element) => {
        element.text = element.dictLabel;
        element.value = element.dictValue;
    });
    cooperationModeColumns.value = res.data;
};
getcooperationMode();
/** 能否破价 */
const getDiscountPrice = async () => {
    const res = await getDicts("hm_discount");
    res.data.forEach((element) => {
        element.text = element.dictLabel;
        element.value = element.dictValue;
    });
    discountPriceColumns.value = res.data;
};
getDiscountPrice();

/** 类目修改 */
const cascaderShade = ref(false)
const cascaderTimeout = ref()

/** 类目最后选择 */
const onFinish = (value) => {
    show.value = false;
    addProductQueryParams.value.productCategoryName = value.selectedOptions
        .map((option) => option.text)
        .join(",");
    addProductQueryParams.value.categoryId = value.selectedOptions
        .map((option) => option.value)
        .join(",");
};
/** 离开页面、提交移除本地存储 */
const removeLocal = () => {
    // 删除app切换导致得缓存数据问题 清除
    localStorage.removeItem('addProductQueryParams')
    productImageList.value && localStorage.removeItem('productImageList')
    voucherImageList.value && localStorage.removeItem('voucherImageList')
    otherImageList.value && localStorage.removeItem('otherImageList')
    customsDeclarationImageList.value && localStorage.removeItem('customsDeclarationImageList')
    customsInformationImageList.value && localStorage.removeItem('customsInformationImageList')
    customsInspectionImageList.value && localStorage.removeItem('customsInspectionImageList')
    customsTestReportImgaeList.value && localStorage.removeItem('customsTestReportImgaeList')
    addProductQueryParams.value = {
        supplierName: "",
        styleName: "",
        category: "",
        productCategoryName: "",
        categoryId: "",
        brandName: "",
        styleCode: "",
        sellingPoints: "",
        tradeMode: "",
        cooperationMode: "",
        price: "",
        costPrice: "",
        liveStreamingMechanism: "",
        commission: "",
        brokerage: "",
        discountPrice: "",
        supplierId: "",
        productImage: "",
        voucherImage: "",
        otherImage: "",
        customsDeclarationImage: "",
        customsInformationImage: "",
        customsInspectionImage: "",
        customsTestReportImgae: "",
        specs: "",
        // ingredient: "",
        warehouse: "",
        groupName: "",

        cooperationMode2: "",
        price2: "",
        costPrice2: "",
        liveStreamingMechanism2: "",
        commission2: "",
        brokerage2: "",

        cooperationMode3: "",
        price3: "",
        costPrice3: "",
        liveStreamingMechanism3: "",
        commission3: "",
        brokerage3: "",
        deliveryTime: "",
        placeDelivery: "",
        placeDeliveryId: "",
        logistics: "",
        eligibility: "",
        factoryStockNum: "",
        noSendArea: "",
        tax: '',
        historyPrice: "",
    }
    productImageList.value = []
    voucherImageList.value = []
    otherImageList.value = []
    customsDeclarationImageList.value = []
    customsInformationImageList.value = []
    customsInspectionImageList.value = []
    customsTestReportImgaeList.value = []
}
/**
 * 图片全路径转半路径
 * @param list 
 */
const getPicByfullPath = (list: any[]) => {
    if (list.length > 0) {
        const updatedList = list.map((item: any) => {
            return item.url.split(getEnvValue("VITE_APP_PIC_URL"))[1];
        });
        return updatedList.join(',');
    } else {
        return '';
    }
}
const onSubmit = async () => {
    loading.value = true
    const list = JSON.parse(JSON.stringify(addProductQueryParams.value));
    list.productImage = getPicByfullPath(productImageList.value)
    list.voucherImage = getPicByfullPath(voucherImageList.value)
    list.otherImage = getPicByfullPath(otherImageList.value)
    list.customsDeclarationImage = getPicByfullPath(customsDeclarationImageList.value)
    list.customsInformationImage = getPicByfullPath(customsInformationImageList.value)
    list.customsInspectionImage = getPicByfullPath(customsInspectionImageList.value)
    list.customsTestReportImgae = getPicByfullPath(customsTestReportImgaeList.value)
    if (list.cooperationMode == "供货") {
        delete list.price;
        delete list.commission
        delete list.brokerage
    }
    if (list.cooperationMode2 == "供货") {
        delete list.price2;
        delete list.commission2
        delete list.brokerage2
    }
    if (list.cooperationMode3 == "供货") {
        delete list.price3;
        delete list.commission3
        delete list.brokerage3
    }
    list.hmMechanismsList = [
        { cooperationMode: list.cooperationMode, commission: list.commission, price: list.price, costPrice: list.costPrice, brokerage: list.brokerage, liveStreamingMechanism: list.liveStreamingMechanism },
        { cooperationMode: list.cooperationMode2, commission: list.commission2, price: list.price2, costPrice: list.costPrice2, brokerage: list.brokerage2, liveStreamingMechanism: list.liveStreamingMechanism2 },
        { cooperationMode: list.cooperationMode3, commission: list.commission3, price: list.price3, costPrice: list.costPrice3, brokerage: list.brokerage3, liveStreamingMechanism: list.liveStreamingMechanism3 },

    ]
    // 贸易方式
    list.tradeMode = tradeModeChecked.value
    // 能否破价
    list.discountPrice = discountPriceChecked.value
    // 走仓
    list.warehouse = warehouseChecked.value
    try {
        await addHmProducts(list);
        loading.value = false
        loadingback.value = true;
        showSuccessToast({ type: "success", message: "新增商品成功" });
        removeLocal();
        router.back();
    } catch (error) {
        if (error == 'timeout') {
            showFailToast('新增商品失败');
        }
        loading.value = false
    }
};

/** 删除 */
const deleteImg = (list: any, index: number) => {
    list.splice(index, 1);
};
/** app端隐藏触发保存表单 */
(window as any).saveState = function (arg) {
    if (arg.action == 'save') {
        localStorage.setItem("addProductQueryParams", JSON.stringify(addProductQueryParams.value));
        localStorage.setItem("mechanismArr", JSON.stringify(mechanismArr.value));
        if (productImageList.value.length > 0) {
            localStorage.setItem("productImageList", JSON.stringify(productImageList.value));
        }
        if (voucherImageList.value.length > 0) {
            localStorage.setItem("voucherImageList", JSON.stringify(voucherImageList.value));
        }
        if (otherImageList.value.length > 0) {
            localStorage.setItem("otherImageList", JSON.stringify(otherImageList.value));
        }
        if (customsDeclarationImageList.value.length > 0) {
            localStorage.setItem("customsDeclarationImageList", JSON.stringify(customsDeclarationImageList.value));
        }
        if (customsInformationImageList.value.length > 0) {
            localStorage.setItem("customsInformationImageList", JSON.stringify(customsInformationImageList.value));
        }
        if (customsInspectionImageList.value.length > 0) {
            localStorage.setItem("customsInspectionImageList", JSON.stringify(customsInspectionImageList.value));
        }
        if (customsTestReportImgaeList.value.length > 0) {
            localStorage.setItem("customsTestReportImgaeList", JSON.stringify(customsTestReportImgaeList.value));
        }
    }
}
onUnmounted(() => {
    removeLocal();
    clearTimeout(cascaderTimeout.value)
})
/** app端重新打开后数据保存重新渲染 */
const rendering = () => {
    if (localStorage.getItem('addProductQueryParams')) {
        addProductQueryParams.value = JSON.parse(localStorage.getItem('addProductQueryParams') as string)
    }
    if (localStorage.getItem('mechanismArr')) {
        mechanismArr.value = JSON.parse(localStorage.getItem('mechanismArr') as string)
    }
    if (localStorage.getItem('productImageList')) {
        productImageList.value = JSON.parse(localStorage.getItem('productImageList') as string)
    }
    if (localStorage.getItem('voucherImageList')) {
        voucherImageList.value = JSON.parse(localStorage.getItem('voucherImageList') as string)
    }
    if (localStorage.getItem('otherImageList')) {
        otherImageList.value = JSON.parse(localStorage.getItem('otherImageList') as string)
    }
    if (localStorage.getItem('customsDeclarationImageList')) {
        customsDeclarationImageList.value = JSON.parse(localStorage.getItem('customsDeclarationImageList') as string)
    }
    if (localStorage.getItem('customsInformationImageList')) {
        customsInformationImageList.value = JSON.parse(localStorage.getItem('customsInformationImageList') as string)
    }
    if (localStorage.getItem('customsInspectionImageList')) {
        customsInspectionImageList.value = JSON.parse(localStorage.getItem('customsInspectionImageList') as string)
    }
    if (localStorage.getItem('customsTestReportImgaeList')) {
        customsTestReportImgaeList.value = JSON.parse(localStorage.getItem('customsTestReportImgaeList') as string)
    }

}
rendering()
/** 图片放大 */
const enlargeImage = (img: string) => {
    if (img) {
        showImagePreview({
            images: [img],
        });
    }
};
(window as any).msgFromUniapp = function (arg) {
    const imageLists = {
        productImage: productImageList.value,
        voucherImage: voucherImageList.value,
        otherImage: otherImageList.value,
        customsDeclarationImage: customsDeclarationImageList.value,
        customsInformationImage: customsInformationImageList.value,
        customsInspectionImage: customsInspectionImageList.value,
        customsTestReportImgae: customsTestReportImgaeList.value
    };

    const maxCounts = {
        productImage: 5,
        voucherImage: 5,
        otherImage: 10,
        customsDeclarationImage: 5,
        customsInformationImage: 5,
        customsInspectionImage: 5,
        customsTestReportImgae: 5
    };

    const imageList = imageLists[arg.name];
    const maxCount = maxCounts[arg.name];

    handleImageUpdate(imageList, arg, maxCount);
};
const postImage = (name: string, count: number) => {
    (window as any).uni.webView.postMessage({
        data: {
            type: "img",
            count: count,
            name: name,
            url: getEnvValue("VITE_APP_UPLOAD_API") + '/resource/oss/upload',
            header: {
                Authorization: `Bearer ${token.value}`,
                clientid: "e5cd7e4891bf95d1d19206ce24a7b32e",
            },
        },
    });
};

</script>
<style lang="less" scoped>
.dragge_box {
    display: contents;
    // align-items: center;
    // flex-wrap: wrap;
}

.cascaderShade {
    width: 100%;
    height: 100%;
    position: absolute;
    z-index: 9999;
}

:deep(.van-nav-bar__left .van-icon) {
    color: #1a1b1c !important;
}

:deep(.van-field__label) {
    width: 100px !important;
}

.operationBasicsDetail {
    width: 100%;
    //   height: 100vh;
    background: #f6faff;
    box-sizing: border-box;
    display: flex;
    flex-wrap: wrap;
    align-content: space-between;
    justify-content: center;
    align-content: flex-start;

    .header {
        background: linear-gradient(#CDECFF 0%, #FFFFFF 70%);
        filter: blur(0px);
        height: 90px;
        padding-top: 44px;
        box-sizing: border-box;
        width: 100%;
        position: fixed;
        z-index: 6003;

        :deep(.van-icon-arrow-left) {
            color: #1a1b1c !important;
        }

        :deep(.van-nav-bar) {
            background: none !important;
        }

        :deep(.van-nav-bar__content) {
            background-color: transparent !important;
        }
    }

    //浮动导航
    .hmshop-floating-nav {
        position: fixed;
        top: 90px;
        display: flex;
        align-items: center;
        background-color: white;
        z-index: 999;
        width: 100%;
        height: 34px;
        align-content: center;
        color: #b8beca;
        box-shadow: 0px 4px 8px 0px rgba(189, 195, 204, 0.5);
        border: 1px solid #F3F3FF;

        ul {
            list-style: none;
            padding: 0 10px;
            box-sizing: border-box;
            margin: 0;
            display: flex;
            align-items: center;
            justify-content: space-around;
            width: 100%;

            li {
                width: 0px;
                flex: 1;
                font-family: PingFangSC, PingFang SC;
                font-weight: 400;
                font-size: 14px;
                color: #8492AD;
                line-height: 14px;
                text-align: center;
                font-style: normal;
                text-transform: lowercase;
            }

            .red-text {
                color: #0094FF;
                /* 激活状态下字体变为红色 */
            }
        }
    }

}

.add_product {
    background-color: #f6faff;
    width: 100%;
    height: calc(100vh - 90px);
    box-sizing: border-box;
    padding: 0px 15px 94px 15px;
    margin-top: 90px;
    overflow-y: scroll;
}

.imgform {
    :deep(.van-cell) {
        border-bottom: none !important;


    }
}

.form_item {


    :deep(.van-cell) {
        padding: 20px 0;
        border-bottom: 1px solid #F3F3FF;


    }

    :deep(.van-cell-group):last-child {

        .van-cell {
            border-bottom: none !important;
        }

    }

    :deep(.van-field__label) {

        color: #464E5D !important;
    }

    :deep(.van-field__label--required) {
        &::before {
            display: none;
        }

        &::after {
            color: var(--van-field-required-mark-color);
            content: "*";
        }
    }
}

.add_supplier-background {
    height: 100vh;
    min-height: 850px;
    background-color: #fff;

    .mechanism_title {
        // width: 100%;
        font-weight: 600;
        font-size: 14px;
        color: #1A1B1C;
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin: 10px 15px 10px 15px;

        .delete_mechanism {
            width: 128px;
            height: 34px;
            border-radius: 22px;
            border: 1px solid #FC2540;
            display: flex;
            justify-content: center;
            align-items: center;
            font-weight: 400;
            font-size: 14px;
            color: #FC2540;

            .van-image {
                width: 14px;
                height: 14px;
            }
        }
    }

    .add_mechanism {
        width: 128px;
        height: 34px;
        border-radius: 22px;
        border: 1px solid #0094FF;
        display: flex;
        justify-content: center;
        align-items: center;
        font-weight: 400;
        font-size: 14px;
        color: #0094FF;
        margin: auto;

        .van-image {
            width: 14px;
            height: 14px;
        }
    }
}

:deep(.van-cell-group--inset) {
    margin: 0 !important;
    border-radius: 0 !important;
}

.label {
    width: 90px;
    margin-right: 12px;
}

.value {
    width: 100%;
    display: flex;
    flex-wrap: wrap;

    .imgList {
        position: relative;

        .loading_pic {
            width: 90px;
            height: 90px;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        :deep(.van-image__img) {
            margin-right: 5px;
        }

        :deep(.van-icon) {
            position: absolute;
            top: 0;
            z-index: 100;
            right: 4px;
            font-size: 10px;
            height: 15px;
            width: 15px;
            background-color: #000;
            border-bottom-left-radius: 16px;
            display: flex;
            justify-content: center;
            align-items: center;
        }

        :deep(.van-icon-cross:before) {
            margin: 0 0 1px 2px;
        }
    }

    :deep(.van-image__img) {
        width: 90px;
        height: 90px;
    }
}

:deep(.van-form) {
    // padding-bottom: 35px !important;
    background-color: #fff;
}

:deep(.van-popup--bottom) {
    border-radius: 20px 20px 0px 0px !important;
}

:deep(.van-picker-column__item--selected>.van-ellipsis) {
    color: #0094ff;
}

.image-title {
    font-weight: 400;
    font-size: 14px;
    color: #464E5D;
    line-height: 14px;
    margin-top: 20px;
}

.card-title {
    font-weight: 400;
    font-size: 12px;
    color: #8492AD;
    line-height: 12px;
}

.mess_line {
    height: 10px;
    background-color: #f6faff;
}

.message_title_box {
    background: linear-gradient(270deg, #FFFFFF 0%, #CDECFF 100%);
    height: 46px;
    width: 100%;
    position: relative;
    box-sizing: border-box;
    padding: 4px;
    display: flex;
    align-items: center;

    .chilunimg {
        width: 46px;
        height: 37px;
        background: url("@/assets/newui/form/icon_jizhitubiao.jpg");
        background-repeat: no-repeat;
        background-size: 100% 100%;
        margin-right: 10px;
        transform: scale(0.68);
    }

    .jz1_img {
        width: 54px;
        height: 16px;
        background: url("@/assets/newui/details/icon_jizhiyilan@2x.png");
        background-repeat: no-repeat;
        background-size: 100% 100%;
    }

    .jz2_img {
        width: 54px;
        height: 16px;
        background: url("@/assets/newui/details/icon_jizhierlan@2x.png");
        background-repeat: no-repeat;
        background-size: 100% 100%;
    }

    .jz3_img {
        width: 54px;
        height: 16px;
        background: url("@/assets/newui/details/icon_jizhisanlanse@2x.png");
        background-repeat: no-repeat;
        background-size: 100% 100%;
    }
}

.mess_card {
    border-radius: 5px;
    overflow: hidden;

}

.mt-10 {
    margin-top: 10px
}

:deep(.van-form) {
    background-color: #ffffff00;
}

.add_jizhi_bt {
    width: 128px;
    height: 34px;
    background: #F6FAFF;
    border-radius: 22px;
    border: 1px solid #0094FF;
    margin: 0 auto;
    margin-top: 16px;
    display: flex;
    justify-content: center;
    align-items: center;
    font-weight: 400;
    font-size: 14px;
    color: #0094FF;
    line-height: 14px;

    .add_img {
        width: 14px;
        height: 14px;
        background: url("@/assets/newui/form/icon_tianjia.svg");
        background-repeat: no-repeat;
        background-size: 100% 100%;
        margin-right: 9px;
    }
}

.del_jizhi_bt {
    width: 128px;
    height: 34px;
    background: #F6FAFF;
    border-radius: 22px;
    border: 1px solid #FC2540;
    margin: 0 auto;
    margin-top: 16px;
    display: flex;
    justify-content: center;
    align-items: center;
    font-weight: 400;
    font-size: 14px;
    color: #FC2540;
    line-height: 14px;
    margin-bottom: 10px;

    .del_img {
        width: 14px;
        height: 14px;
        background: url("@/assets/newui/form/icon_shanchu.svg");
        background-repeat: no-repeat;
        background-size: 100% 100%;
        margin-right: 9px;
    }
}

.form_foot {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 84px;
    background: #FFFFFF;
    box-shadow: 0px 0px 8px 0px rgba(189, 195, 204, 0.5);
    box-sizing: border-box;
    padding: 20px 15px;
    z-index: 110;
}

.product_detail_top--heng {
    height: 10px;
}

:deep(textarea) {
    word-break: break-all !important;

}

// van-badge__wrapper van-icon van-icon-arrow van-cell__right-icon</style>